package com.icesoft.system.sender.sms.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.icesoft.framework.core.util.StringUtils;
import com.icesoft.system.sender.sms.SmsSender;
import com.icesoft.system.types.SmsTypeDictionary;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class ALiYunTemplateServiceImpl implements SmsSender {

	private final SmsTypeDictionary smsType;

	private Client createAliSmsClient() throws Exception {
		Config config = new Config()
				.setAccessKeyId(smsType.getAccessKeyId())
				.setAccessKeySecret(smsType.getAccessKeySecret());
		// 访问的域名
		config.endpoint = smsType.getEndpoint();
		return new Client(config);
	}

	@Override
	public boolean sendSmsCode(String phone, String code) throws Exception {
		log.info("短信验证码：手机号：{}，验证码：{}", phone, code);
		com.aliyun.dysmsapi20170525.Client client = this.createAliSmsClient();
		String SignName = smsType.getSignName();
		String TemplateCode = smsType.getTemplateCode();
		String TemplateParam = StringUtils.format(smsType.getTemplateParam(), code);
		SendSmsRequest sendSmsRequest = new SendSmsRequest()
				.setPhoneNumbers(phone)
				.setSignName(SignName)
				.setTemplateCode(TemplateCode)
				.setTemplateParam(TemplateParam);
		// 复制代码运行请自行打印 API 的返回值
		SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
		log.debug("短信回执：code:{} ; msg:{}", sendSmsResponse.getBody().getCode(), sendSmsResponse.getBody().getMessage());
		return true;
	}

	@Override
	public boolean sendSms(String phone, String msg, String SignName, String TemplateCode, String TemplateParam) throws Exception {
		log.info("手机号：{}，短信：{}", phone, msg);
		com.aliyun.dysmsapi20170525.Client client = this.createAliSmsClient();
		SendSmsRequest sendSmsRequest = new SendSmsRequest()
				.setPhoneNumbers(phone)
				.setSignName(SignName)
				.setTemplateCode(TemplateCode)
				.setTemplateParam(TemplateParam);
		// 复制代码运行请自行打印 API 的返回值
		SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
		log.debug(sendSmsResponse.getBody().toString());
		return true;
	}
}
